<?php
/**
 * Created by muniao.
 * User: muniao
 * Date: 2018/7/31
 * Time: 16:00
 */

namespace app\api\controller\deliver\v1;


use think\Cache;
use think\Controller;
use app\api\model\Authority;
use think\db;
use app\index\model\Jpush;
use think\Request;
use  app\api\model\OrderModel;

class Transfer extends Controller
{
    
    protected $us;
    
    public function _initialize()
    {
        $model    = new Authority();
        $this->us = $model->check(1);
    }
    
    /*
      * 转派记录添加
      */
    public function record(Jpush $jpush)
    {
        $data        = \request()->post();
        $OrderUserId = db('order')
            ->where(['order.order_id' => $data['order_id']])
            ->find();
        $receiving_permission=db('dispatch_config_chanel', config('database.zong'))->where('chanel_id',$OrderUserId['channel_details'])->value('receiving_permission');
        
        if ($OrderUserId['pro_id']==1) {
            $value ='wall_renovation_level';
        } elseif ($OrderUserId['pro_id'] == 3) {
            $value ='partial_renovation_level';
        } elseif ($OrderUserId['pro_id'] == 42 ) {
            $value = 'waterproof_repair_level';
        } elseif ($OrderUserId['pro_id'] == 104) {
            $value = 'maintenance_installation_level';
        }else{
            $value = 'miscellaneous_level';
        }
        $dispatch_config_user=db('dispatch_config_user', config('database.zong'))->where('user_id',$data['user_id'])->value($value);
        if($receiving_permission==2){
            $dispatch_config_user_chanel =db('dispatch_config_user_chanel', config('database.zong'))->where('chanel_id',$OrderUserId['channel_details'])->where('user_id',$data['user_id'])->find();
            if(empty($dispatch_config_user_chanel)){
                r_date(null, 300, '该渠道开启了接单权限要求，该店长未拥有该渠道的接单权限');
            }
        }
        $dispatch_config_blacklist=db('dispatch_config_blacklist', config('database.zong'))->where('chanel_id',$OrderUserId['channel_details'])->where('dispatch_config_blacklist.city_id', config('cityId'))->where('user_id',$data['user_id'])->find();
        if(!empty($dispatch_config_blacklist)){
            r_date(null, 300, '该店长已被纳入该渠道黑名单，不可接此订单');
        }
        $order_transfer_record=db('order_transfer_record')
            ->where(['order_transfer_record.order_id' => $data['order_id']])
            ->order('id desc')
            ->find();
        if (!empty($order_transfer_record) && $order_transfer_record['admin_id']==$this->us['user_id'] && $this->us['reserve']==2) {
            r_date(null, 300, '该订单已经转派');
        }
        $reason=json_decode($data['selectJson'], true);
        if(empty($reason)){
            r_date(null, 300, '请添加转派原因');
        }
        $reasonSelect=[];
        foreach ($reason as $o){
            foreach ($o['select'] as $l){
                $reasonSelect[]= $l['title'];
            }
            
        }
        $time = time();
        $op   = \db('transfer_record')->insertGetId([
            'user_id' => $data['user_id'],
            'time' => $time,
            'order_id' => $data['order_id'],
            'operation' => $this->us['user_id'],
        ]);
        $types=1;
        $store_id   = db('user')->where('user_id', $data['user_id'])->value('store_id');
        $business_id = db('business_config', config('database.zong'))->where('find_in_set(:id,store_list)', ['id' => $store_id])->where('status', 1)->value('business_id');
        \db('order_transfer_record')->insertGetId([
            'order_id' => $data['order_id'],
            'original_user_id' => $OrderUserId['assignor'],
            'transfer_user_id' => $data['user_id'],
            'transfer_business_id' => $business_id,
            'transfer_store_id' =>$store_id,
            'types' => $types,
            'admin_role' => 2,
            'order_aggregate' =>  json_encode( db('order_aggregate')->where(['order_id' => $data['order_id']])->find()),
            'order_info' => json_encode(db('order_info')->where(['order_id' => $data['order_id']])->find()),
            'admin_id' => $this->us['user_id'],
            'admin_name' => $this->us['username'],
            'create_time' => $time,
            'reason_json' => $data['selectJson'],
            'reason'=>implode(",",$reasonSelect),
        ]);
        if ($op) {
            $company_id = db('company_config', config('database.zong'))->where('find_in_set(:id,store_list)', ['id' => $store_id])->where('status', 1)->value('company_id');
            \db('order')->where('order_id', $data['order_id'])->update(['assignor' => $data['user_id'], 'company_id' => $company_id,'store_id'=>$store_id,'business_id'=>$business_id]);
            db('message')->where(['order_id' => $data['order_id']])->update(['already' => 0, 'have' => $time]);
            db('remind')->where(['order_id' => $data['order_id']])->update(['tai' => 0]);
            $li = db('order')
                ->field('order.*,st.store_id,st.store_name,us.*,p.province,c.city,y.county')
                ->join('user us', 'order.assignor=us.user_id', 'left')
                ->join('store st', 'us.store_id=st.store_id', 'left')
                ->join('province p', 'order.province_id=p.province_id', 'left')
                ->join('city c', 'order.city_id=c.city_id', 'left')
                ->join('county y', 'order.county_id=y.county_id', 'left')
                ->where(['order.order_id' => $data['order_id']])
                ->find();
            $s  = $li['province'] . $li['city'] . $li['county'] . $li['addres'];
            
            db('remind')->insertGetId([
                'admin_id' => $data['user_id'],
                'order_id' => $data['order_id'],
                'time' => $time,
                'stater' => 1,
                'tai' => 1,
            ]);
            $content = "尊敬的{$li['username']}店长您好！客户:{$li['contacts']}，地址:{$s}，电话:{$li['telephone']}，订单：{$li['order_no']}来了，请尽快联系客户预约上门服务。如有任何问题都可致电4000-987-009,回T退订";
            if (!empty($li['registrationId'])) {
                $data = array('order_id' => $data['order_id'], 'content' => $content, 'type' => 6, 'user_id' => $data['user_id']);
                $jpush->tui($content, $li['registrationId'], $data);
            }
            db('through')->where('order_ids', $data['order_id'])->update(['handle' => $time]);
            \db('workbench_read')->where('order_id', $data['order_id'])->update(['have' =>$time, 'already' => 0]);
            \db('order_extend_info')->where('order_id', $data['order_id'])->update(['user_level' => $dispatch_config_user]);
            $order_times = db('order_times')->where('order_id', $data['order_id'])->find();
            if ($order_times) {
                db('order_times')->where('order_id', $data['order_id'])->update(['turn_time' => $time]);
            }
            $orderSMS = json_decode(sendOrder($data['order_id']), true);
            if ($orderSMS['code'] != 200) {
                r_date('', 300, '编辑失败');
            }
            r_date('', 200);
        }
        r_date('', 300, '添加失败');
    }
    /*
     * 转派原因
     */
    public function reason(){
        $sys_config       = Db::connect(config('database.zong'))->table('sys_config')->where('keyss', 'order_transfer_reason')->value('valuess');
        $sys_config       = json_decode($sys_config, true);
        r_date($sys_config, 200);
    }
    /*
    * 转派列表查询当前订单是否转派状态
    */
    public function transferInformation(){
        $data         = Authority::param(['orderId']);
        $transfer_record_confirm=\db('transfer_record_confirm')->join('user','user.user_id=transfer_record_confirm.user_id','left')->field('user.username,FROM_UNIXTIME(transfer_record_confirm.create_time,"%Y-%m-%d %H:%i:%s") as time,if(transfer_record_confirm.confirm=0,"转派中","") as title')->where('order_id',$data['orderId'])->where('confirm',0)->find();
        r_date($transfer_record_confirm, 200);
    }
    /*
 * 转派列表查询当前订单是确认
 */
    public function transferConfirmation(){
       
        r_date(null, 200);
    }
}